import * as mysql from 'mysql';
// 尝试连接到 MySQL
const Dbconnect = (callback: (conn: mysql.Connection) => void) => {
    let dbConnection: mysql.Connection;
    dbConnection = mysql.createConnection({
        host: 'localhost',
        user: 'root',
        password: 'root',
        database: 'hcpapper',
        port: 3306   //MySQL 的默认端口号
    });
    // 开始连接
    dbConnection.connect(function (err) {
        if (err) {
            console.error('Error connecting to MySQL:', err);
            setTimeout(Dbconnect, 2000); // 重新连接的延迟时间
        } else {
            console.log('Connected to MySQL');
            callback(dbConnection);
        }
    });

    dbConnection.on('error', function (err) {
        console.error('MySQL error:', err);
        if (err.code === 'PROTOCOL_CONNECTION_LOST') {
            console.log('Reconnecting to MySQL...');
            Dbconnect(callback);
        } else {
            throw err;
        }
    });
    dbConnection.on('end', function () {
        console.log('MySQL close.')
    })
    return dbConnection
}

const useDatabase = (ipcMain: Electron.IpcMain) => {
    ipcMain.on('dbQuery', (event, responseChannel: string, sql: string, values: []) => {
        console.log('db query: ', sql)
        Dbconnect((conn) => {
            conn.query(sql, values, (err, result) => {
                if (!err) {
                    event.sender.send(responseChannel, result)
                    conn.end()
                } else {
                    console.log('db err:', err)
                }
            })
        })
    })
}

export { useDatabase }